package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author げっしょく
 * @date 2021/11/20
 */
@Service
@Transactional
@Slf4j
public class ApUserLoginServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserLoginService {
    /**
     * 判断用户登录
     * @param dto 手机号和密码
     * @return
     */
    @Override
    public ResponseResult UserLogin(LoginDto dto) {
        //判断手机号和密码是否为空
        if (StringUtils.isNotEmpty(dto.getPhone()) && StringUtils.isNotEmpty(dto.getPassword())) {
            //手机密码不为空,通过手机号查找数据库信息
            LambdaQueryWrapper<ApUser> lam = new LambdaQueryWrapper<>();
            lam.eq(ApUser::getPhone, dto.getPhone());
            ApUser user = getOne(lam);
            if (user == null) {
                //查询结果为null,直接返回手机号错误
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "手机号错误");
            }
            //判断密码是否相等
            String password = DigestUtils.md5DigestAsHex((dto.getPassword() + user.getSalt()).getBytes());
            if (!password.equals(user.getPassword())) {
                //密码不相等,返回密码错误
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //生成Token
            String token = AppJwtUtil.getToken(user.getId().longValue());
            //封装Map(token和用户信息),盐值和密码不返回
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            user.setSalt("");
            user.setPassword("");
            map.put("user", user);
            return ResponseResult.okResult(map);

        }else {
            //游客登录
            //通过0生成生成token,封装Map
            Map<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(0L));
            //直接返回Map
            return ResponseResult.okResult(map);
        }
    }
}
